﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Models;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using StackExchange.Profiling.Internal;

namespace Aioms.Controllers
{
    /// <summary>
    /// 巡检路线
    /// </summary>
    [DynamicApiController]
    public class InspectionLineController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public InspectionLineController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostList([FromForm] long eid, [FromForm] string content)
        {
            RefAsync<int> total = 0;
            List<InspectionLine> inspectionLines = await db.Queryable<InspectionLine>()
                .Where(il => il.IsDel == 0)
                .Where(il => il.Eid == eid)
                .WhereIF(!string.IsNullOrEmpty(content), il => il.Name.Contains(content))
                .OrderBy(il => il.SortId, OrderByType.Asc).ToListAsync();
            UnifyContext.Fill(new { Total = total.Value });
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = inspectionLines,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 巡检路线新增
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="inspection"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostSave([FromForm] long eid, [FromForm] InspectionLine inspection)
        {
            long id = await db.Insertable<InspectionLine>(inspection).ExecuteReturnBigIdentityAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = id,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }


        public async Task<IActionResult> PostDelete([FromForm] long eid, [FromForm] long ilid)
        {
            // 第一步：删除巡检路线
            await db.Updateable<InspectionLine>().SetColumns(il => il.IsDel == 1).Where(il => il.Eid == eid && il.Id == ilid).ExecuteCommandAsync();
            // 第二步：删除巡检点
            List<long> ipids = await db.Queryable<InspectionPoint>().Where(ip => ip.Eid == eid && ip.Ilid == ilid).Select(ip => ip.Id).ToListAsync();
            await db.Updateable<InspectionPoint>().SetColumns(ip => ip.IsDel == 1).Where(ip => ip.Eid == eid && ip.Ilid == ilid).ExecuteCommandAsync();
            // 第三步：删除巡检项
            await db.Deleteable<InspectionOption>().Where(io => io.Eid == eid)
                .Where(io => ipids.Contains(io.Ipid))
                .ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 巡检路线修改
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="inspection"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostUpdate([FromForm] long eid, [FromForm] InspectionLine inspection)
        {
            await db.Updateable<InspectionLine>(inspection).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 路线拖动
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="strareas"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostTuodong([FromForm] long eid, [FromForm] string strareas)
        {
            List<InspectionLine> inspectionLines = JsonConvert.DeserializeObject<List<InspectionLine>>(strareas);
            foreach (var il in inspectionLines)
            {
                await db.Updateable<InspectionLine>().SetColumns(a => a.SortId == inspectionLines.IndexOf(il)).Where(a => a.Id == il.Id && a.Eid == eid).ExecuteCommandAsync();
            }
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = null,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
